package com.qf.air.util;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;

/**
 * 写字楼里写字间，写字间里程序员；
 * 程序人员写程序，又拿程序换酒钱。
 * 酒醒只在网上坐，酒醉还来网下眠；
 * 酒醉酒醒日复日，网上网下年复年。
 * 但愿老死电脑间，不愿鞠躬老板前；
 * 奔驰宝马贵者趣，公交自行程序员。
 * 别人笑我忒疯癫，我笑自己命太贱；
 * 不见满街漂亮妹，哪个归得程序员？
 *
 * @version v1.0
 * @authorLenovo
 * @date2021/11/4
 */
public class SearchUtil {
    public static SearchResponse search(Integer page, Integer rows, Integer districtId, String monitoringStation, Date startTime, Date endTime) throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (districtId==null || districtId==0){
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("districtId",districtId));
        }
        if (!StringUtils.isEmpty(monitoringStation)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("monitoringStation",monitoringStation));
        }
        if (startTime!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("startTime",startTime));
        }
        if (endTime!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("endTime",endTime));
        }
        sourceBuilder.from(page);
        sourceBuilder.size(rows);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.fragmentSize(2);
        highlightBuilder.preTags("<span style='color:yellow;'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.field("monitoringStation");
        sourceBuilder.highlighter(highlightBuilder);
        sourceBuilder.query(boolQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse search = ElasticsearchUtil.getClient().search(request, RequestOptions.DEFAULT);
        return search;
    }
}
